package com.example.administrator.myapplication.contact;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.example.administrator.myapplication.L;
import com.example.administrator.myapplication.PermissionUtil;
import com.example.administrator.myapplication.R;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by wq on 2018/11/26.
 */
public class ContactActivity3 extends Activity {


private TextView tv_text ;
private EditText et_num ;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_text = (TextView) findViewById(R.id.tv_text);
        et_num = (EditText) findViewById(R.id.et_num);
//        checkPermissions();
        PermissionUtil.requestPermission(this, PermissionUtil.needPermissions);//权限申请；

//            String json = new Gson().toJson(ContanctActivity5.getContanct(this));
//            Log.d("====json",ContanctActivity5.getContanct(this).size() +json);
//            et_num.setText(ContanctActivity5.getContanct(this).size() +json); ;
        try {
//            getContactInfo();
            queryContactPhoneNumber();
//            ContanctActivity5.getContancta(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    private void checkPermissions() {
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(ContactActivity3.this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_CONTACTS);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(ContactActivity3.this, permissions, 1);
        } else {


        }

    }

    private JSONArray contactData2;
    private JSONObject jsonObject2;


    private void queryContactPhoneNumber() throws JSONException{
        contactData2 = new JSONArray();

        String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                cols, null, null, null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            jsonObject2 = new JSONObject();
            contactData2.put(jsonObject2);
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String name = cursor.getString(nameFieldColumnIndex);
            String number = cursor.getString(numberFieldColumnIndex);

            jsonObject2.put("name", name);
            jsonObject2.put("phone", number);
            Log.d("=====nnnn",name + "====="+ number);

        }
        et_num.setText(cursor.getCount()+"==="+contactData2.toString());
        cursor.close();

        Log.d("====json",contactData2.toString());


    }
    private JSONArray contactData;
    private JSONObject jsonObject;
    public String getContactInfo() throws JSONException {
        Log.d("====te","1111111");
        // 获得通讯录信息 ，URI是ContactsContract.Contacts.CONTENT_URI
        contactData = new JSONArray();
        String mimetype = "";
        int oldrid = -1;
        int contactId = -1;
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Data.RAW_CONTACT_ID);
        int numm = 0;
        while (cursor.moveToNext()) {
            contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
            if (oldrid != contactId) {
                jsonObject = new JSONObject();
              /*  if (!TextUtils.isEmpty(jsonObject.get("name").toString())&&!TextUtils.isEmpty(jsonObject.get("phone").toString())) {
                    contactData.put(jsonObject) ;

                    Log.v("=====cccddd",numm+"==="+jsonObject.get("name").toString() + "====" +jsonObject.get("phone").toString());
                }*/

//                Log.d("=====sssdd","111111111111111");

                contactData.put(jsonObject) ;
//                contactData.put("contact" + numm, jsonObject);
                numm++;
                oldrid = contactId;
            }
            Log.d("=====sssdd",contactId+"");
            // 取得mimetype类型
            mimetype = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
            // 获得通讯录中每个联系人的ID
            // 获得通讯录中联系人的名字
            if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mimetype)) {
                String lastname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                jsonObject.put("name", lastname);
                if (jsonObject.has("name")) {
                    Log.d("=====sss",jsonObject.getString("name")+"==="+numm);
                }

            }
            // 获取电话信息
            if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {
                // 取出电话类型
                int phoneType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                // 手机
                if (phoneType == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
                    String mobile = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    jsonObject.put("phone", mobile);

                    Log.d("=====sss",jsonObject.getString("phone")+"==="+numm);
                }

            }
        }
        cursor.close();
        L.i(contactData.toString());
        return contactData.toString();
    }
}
